<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="tabsChangeClick">
      <el-tab-pane label="肠菌样本" name="first">
        <el-card shadow="never" v-if="!(viewDetailsData || viewReportData)">
          <template #header>
            <el-form ref="form" :model="queryParams" :inline="true" style="float: left;margin-right: 40px;">
              <el-form-item prop="number" label="样本编号">
                <el-input v-model="queryParams.number" placeholder="样本编号" clearable @keyup.enter="getReportSampleData('REPORT')" />
              </el-form-item>
              <el-form-item prop="userName" label="用户名">
                <el-input v-model="queryParams.userName" placeholder="用户名" clearable @keyup.enter="getReportSampleData('REPORT')" />
              </el-form-item>
              <el-form-item prop="status" label="样本状态">
                <el-select v-model="queryParams.status" placeholder="样本状态" @change="getReportSampleData('REPORT')">
                  <el-option label="样本已收到" value="SAMPLE_RECEIVE"></el-option>
                  <el-option label="实验室测序完成" value="REPORT_SEQ_END"></el-option>
                  <el-option label="数据分析中" value="DATA_ANALYSIS"></el-option>
                  <el-option label="样本审核中" value="REPORT_AUDIT"></el-option>
                  <el-option label="完成" value="COMPLETED"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="getReportSampleData('REPORT')" icon="el-icon-search"
                  style="margin-right: 10px;">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
            <!-- <el-button type="success" @click="syncSample()"><i class="el-icon-refresh"></i> 同步样本数据</el-button> -->
          </template>
          <el-table v-loading="loading" :data="dataList" highlight-current-row border :cell-style="cellStyle">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" width="55" type="index" />
            <el-table-column label="用户名" prop="userName" width="80" />
            <el-table-column label="样本编号" prop="number">
              <template slot-scope="scope">
                <template
                  v-if="scope.row.auditPass != null && !scope.row.auditPass && scope.row.sampleStatus == 'REPORT_AUDIT'">
                  <el-tooltip class="item" effect="dark" :content="scope.row.auditResult" placement="right">
                    <a href="javascript:;" style="color: red;" @click="samplePdf(scope.row.id)">{{
                      scope.row.number }}</a>
                  </el-tooltip>
                </template>
                <template v-else>
                  <a href="javascript:;" @click="samplePdf(scope.row)">{{ scope.row.number }}</a>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="样本状态" prop="statusText" width="100">
              <template slot-scope="scope">
                <template
                  v-if="scope.row.auditPass != null && !scope.row.auditPass && scope.row.sampleStatus == 'REPORT_AUDIT'">
                  <p style="color: red;">{{ scope.row.statusText }}</p>
                </template>
                <template v-else>{{ scope.row.statusText }}</template>
              </template>
            </el-table-column>
            <el-table-column label="签收时间" prop="signDate" />
            <el-table-column fixed="right" label="操作" min-width="420" width="460">
              <template #default="scope">
                <el-button type="primary" size="small" link @click="viewDetails(scope.row)">查看</el-button>
                <template v-if="scope.row.processStatus == 'SX_PROCESS_START'">
                  <el-button type="info" size="small" link @click="sendKafka(scope.row)"
                    icon="el-icon-s-promotion" disabled="true">发送至Kafka</el-button>
                </template>
                <template v-else>
                  <el-button type="info" size="small" link @click="sendKafka(scope.row)"
                    icon="el-icon-s-promotion">
                    <template v-if="!scope.row.processStatus">发送至Kafka</template>
                    <template v-else>
                      <template v-if="scope.row.processStatus == 'SX_PROCESS_SUCCESS' || scope.row.processStatus == 'INITIALIZE'">发送至Kafka</template>
                      <template v-if="scope.row.processStatus == 'SX_PROCESS_FAIL'">重新发送至Kafka</template>
                    </template>
                  </el-button>
                </template>
                
                <el-button type="primary" size="small" link @click="copyFileUrl(scope.row.id)"
                  icon="el-icon-view">复制地址</el-button>
                <el-button type="primary" size="small" link @click="openUploadFastqDialog(scope.row)"
                  v-if="scope.row.sampleStatus == 'SAMPLE_RECEIVE'" icon="el-icon-upload2">上传FastQ文件</el-button>
                <el-button type="primary" size="small" link @click="markSampleDataFile(scope.row)"
                  v-if="scope.row.sampleStatus == 'REPORT_SEQ_END'" icon="el-icon-place">标记数据完成</el-button>
                <el-button type="warning" size="small" link @click="sampleReportPage(scope.row)"
                  v-if="scope.row.sampleStatus == 'DATA_ANALYSIS' || scope.row.sampleStatus == 'REPORT_AUDIT' || scope.row.sampleStatus == 'COMPLETED'" icon="el-icon-document">样本报告</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="FMT 体检样本" name="third">
        <el-card shadow="never" v-if="!(viewDetailsData || viewReportData)">
          <template #header>
            <el-form ref="form" :model="queryParams" :inline="true" style="float: left;margin-right: 40px;">
              <el-form-item prop="number" label="样本编号">
                <el-input v-model="queryParams.number" placeholder="样本编号" clearable @keyup.enter="getReportSampleData('CHECK_UP')" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="getReportSampleData('CHECK_UP')" icon="el-icon-search"
                  style="margin-right: 10px;">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </template>
          <el-table v-loading="loading" :data="dataList" highlight-current-row border :cell-style="cellStyle">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" width="55" type="index" />
            <el-table-column label="用户名" prop="fmtUserName" width="80" />
            <el-table-column label="样本编号" prop="number">
              <template slot-scope="scope">
                <template>
                  <a href="javascript:;" @click="samplePdf(scope.row)">{{ scope.row.number }}</a>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="所属应用" prop="dfApplicationName" />
            <el-table-column label="关联模板" prop="reportTemplateName" />
            <el-table-column label="本地模板" prop="templateFile" width="165">
              <template slot-scope="scope">
                <template v-if="scope.row.reportTemplateId && (scope.row.templateFile == null || !scope.row.templateFile)">
                  <el-link type="danger">不存在</el-link><el-tag style="margin-left: 8px; cursor: pointer;" @click="copyApplicationTemplate(scope.row)">复制应用模板</el-tag>
                </template>
                <template v-if="scope.row.reportTemplateId && (scope.row.templateFile != null && scope.row.templateFile)">
                  <el-link type="success" @click="sampleTemplateFilePath(scope.row.id)">存在</el-link><el-tag type="danger" style="margin-left: 8px; cursor: pointer;" @click="delSampleTemplateFile(scope.row)">删除本地模板</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime" />
            <el-table-column fixed="right" label="操作" min-width="420" width="460">
              <template #default="scope">
                <el-button type="primary" size="small" link @click="viewDetails(scope.row)">查看</el-button>
                <el-button type="info" size="small" link @click="sendKafka(scope.row)"
                  icon="el-icon-s-promotion">发送至Kafka</el-button>
                <el-button type="primary" size="small" link @click="copyFileUrl(scope.row.id)"
                  icon="el-icon-view">复制地址</el-button>
                  <el-button type="warning" size="small" link @click="sampleReportPage(scope.row)" icon="el-icon-document">样本报告</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </el-card>

      </el-tab-pane>
      <el-tab-pane label="FMT 捐献样本" name="second">
        <el-card shadow="never" v-if="!(viewDetailsData || viewReportData)">
          <template #header>
            <el-form ref="form" :model="queryParams" :inline="true" style="float: left;margin-right: 40px;">
              <el-form-item prop="number" label="样本编号">
                <el-input v-model="queryParams.number" placeholder="样本编号" clearable @keyup.enter="getReportSampleData('FMT')" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="getReportSampleData('FMT')" icon="el-icon-search"
                  style="margin-right: 10px;">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </template>
          <el-table v-loading="loading" :data="dataList" highlight-current-row border :cell-style="cellStyle">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" width="55" type="index" />
            <el-table-column label="用户名" prop="userName" width="80" />
            <el-table-column label="样本编号" prop="number">
              <template slot-scope="scope">
                <template>
                  <a href="javascript:;" @click="samplePdf(scope.row)">{{ scope.row.number }}</a>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="所属应用" prop="dfApplicationName" />
            <el-table-column label="关联模板" prop="reportTemplateName" />
            <el-table-column label="本地模板" prop="templateFile" width="165">
              <template slot-scope="scope">
                <template v-if="scope.row.reportTemplateId && (scope.row.templateFile == null || !scope.row.templateFile)">
                  <el-link type="danger">不存在</el-link><el-tag style="margin-left: 8px; cursor: pointer;" @click="copyApplicationTemplate(scope.row)">复制应用模板</el-tag>
                </template>
                <template v-if="scope.row.reportTemplateId && (scope.row.templateFile != null && scope.row.templateFile)">
                  <el-link type="success" @click="sampleTemplateFilePath(scope.row.id)">存在</el-link><el-tag type="danger" style="margin-left: 8px; cursor: pointer;" @click="delSampleTemplateFile(scope.row)">删除本地模板</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime" />
            <el-table-column fixed="right" label="操作" min-width="420" width="460">
              <template #default="scope">
                <el-button type="primary" size="small" link @click="viewDetails(scope.row)">查看</el-button>
                <el-button type="info" size="small" link @click="sendKafka(scope.row)"
                  icon="el-icon-s-promotion">发送至Kafka</el-button>
                <el-button type="primary" size="small" link @click="copyFileUrl(scope.row.id)"
                  icon="el-icon-view">复制地址</el-button>
                  <el-button type="warning" size="small" link @click="sampleReportPage(scope.row)" icon="el-icon-document">样本报告</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </el-card>

      </el-tab-pane>
      <el-tab-pane label="患者样本" name="patient">
        <el-card shadow="never" v-if="!(viewDetailsData || viewReportData)">
          <template #header>
            <el-form ref="form" :model="queryParams" :inline="true" style="float: left;margin-right: 40px;">
              <el-form-item prop="number" label="样本编号">
                <el-input v-model="queryParams.number" placeholder="样本编号" clearable @keyup.enter="getReportSampleData('FMT')" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="getReportSampleData('FMT')" icon="el-icon-search"
                  style="margin-right: 10px;">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </template>
          <el-table v-loading="loading" :data="dataList" highlight-current-row border :cell-style="cellStyle">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" width="55" type="index" />
            <el-table-column label="用户名" prop="fmtUserName" width="80" />
            <el-table-column label="样本编号" prop="number">
              <template slot-scope="scope">
                <template>
                  <a href="javascript:;" @click="samplePdf(scope.row)">{{ scope.row.number }}</a>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="所属应用" prop="dfApplicationName" />
            <el-table-column label="关联模板" prop="reportTemplateName" />
            <el-table-column label="本地模板" prop="templateFile" width="165">
              <template slot-scope="scope">
                <template v-if="scope.row.reportTemplateId && (scope.row.templateFile == null || !scope.row.templateFile)">
                  <el-link type="danger">不存在</el-link><el-tag style="margin-left: 8px; cursor: pointer;" @click="copyApplicationTemplate(scope.row)">复制应用模板</el-tag>
                </template>
                <template v-if="scope.row.reportTemplateId && (scope.row.templateFile != null && scope.row.templateFile)">
                  <el-link type="success" @click="sampleTemplateFilePath(scope.row.id)">存在</el-link><el-tag type="danger" style="margin-left: 8px; cursor: pointer;" @click="delSampleTemplateFile(scope.row)">删除本地模板</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime" />
            <el-table-column fixed="right" label="操作" min-width="420" width="460">
              <template #default="scope">
                <el-button type="primary" size="small" link @click="viewDetails(scope.row)">查看</el-button>
                <el-button type="info" size="small" link @click="sendKafka(scope.row)"
                  icon="el-icon-s-promotion">发送至Kafka</el-button>
                <el-button type="primary" size="small" link @click="copyFileUrl(scope.row.id)"
                  icon="el-icon-view">复制地址</el-button>
                  <el-button type="warning" size="small" link @click="sampleReportPage(scope.row)" icon="el-icon-document">样本报告</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </el-card>

      </el-tab-pane>
    </el-tabs>

    <!-- 查看文件 -->
    <el-dialog :visible.sync="viewFileVisible" title="上传报告文件" width="750px">
      <div class="viewFileVisible_box">
        <div class="output_file">
          <div class="input_file_top">
            <h3>输出文件</h3>
            <el-upload class="upload-dialog" ref="upload" :action="out_uploadAction" :show-file-list="false"
              :on-change="submitUpload_out" :on-success="uploadFileSuccess_out" :headers="headers" :auto-upload="false">
	              <el-button slot="trigger" style="margin-left: 5px" type="success">上传输出文件（zip）</el-button>
              <div slot="tip" class="el-upload__tip"></div>
            </el-upload>
          </div>
          <el-table :data="outputFileData" border style="width: 100%" max-height="500">
            <el-table-column prop="path" label="文件路径"></el-table-column>
            <el-table-column prop="suffix" label="文件类型"></el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="sendKafkaDialog.visible" title="发送数据到Kafka" width="400px" :close-on-click-modal="false"
      :before-close="closeSendKafkaDialog">
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="选择生信流程" prop="sxProcessId">
          <el-select v-model="sxProcessId">
            <el-option v-for="field in sxProcessList" :key="field.id" :label="field.name" :value="field.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="所属关联模板" prop="reportTemplateId">
          <el-select v-model="formData.reportTemplateId">
            <el-option v-for="field in appTemplateList" :key="field.id" :label="field.name" :value="field.id"></el-option>
          </el-select>
        </el-form-item> -->
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSendKafka">确 定</el-button>
          <el-button @click="closeSendKafkaDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="previewDialog.visible" :title="previewDialog.title" width="900px"
      :close-on-click-modal="false" :before-close="closePreviewDialog">
      <el-button type="success" size="small" link style="float: right; margin-top: 10px; margin-left: 10px;"
          @click="downlaodPdf()">下载报告</el-button>
      <iframe ref="pdfCotainer" :src="pdfUrl" width="100%" height="620px" style="margin-top: 10px;"></iframe>
    </el-dialog>

    <el-dialog :visible.sync="editDialog" title="编辑所属应用" width="400px" :close-on-click-modal="false"
      :before-close="closeEditDialog">
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="所属应用" prop="dfApplicationId">
          <el-select v-model="formData.dfApplicationId" @change="changeApplication">
            <el-option v-for="field in applicationList" :key="field.id" :label="field.name" :value="field.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属关联模板" prop="reportTemplateId">
          <el-select v-model="formData.reportTemplateId">
            <el-option v-for="field in appTemplateList" :key="field.id" :label="field.name" :value="field.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveApplication">确 定</el-button>
          <el-button @click="closeEditDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="uploadFastqDialog.visible" :title="uploadFastqDialog.title" width="500px"
      :before-close="closeUploadFastqDialog">
      <el-form ref="uploadFastqFormRef" :model="uploadFastqFormData" label-width="120px">
        <el-form-item label="FastQ1文件信息" prop="fastq1">
          <el-input v-model="uploadFastqFormData.fastq1" placeholder="请输入FastQ1文件信息" />
        </el-form-item>
        <el-form-item label="FastQ2文件信息" prop="fastq2">
          <el-input v-model="uploadFastqFormData.fastq2" placeholder="请输入FastQ2文件信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="uploadFastq">确 定</el-button>
          <el-button @click="closeUploadFastqDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog width="200px" :visible.sync="uploadReportPdfVisible" title="上传样本报告" :close-on-click-modal="false">
      <div style="height: 40px;">
        <!-- <p style="font-size: 14ox; font-weight: 300; font-style: italic;">报告上传后，由审核人员审核之后将发送给用户！</p>
                    <div style="margin-top: 10px; margin-bottom: 10px;">
                    <el-radio v-model="uploadReport" label="true">重新上传报告</el-radio>
                    <el-radio v-model="uploadReport" label="false">使用已有报告</el-radio>
                </div> -->
        <div>
          <el-upload class="upload-dialog" ref="uploadReport" :action="uploadReportPdfAction" :show-file-list="false"
            :on-change="submitUploadReport" :on-success="uploadReportFileSuccess" :headers="headers" :auto-upload="false">
            <el-button slot="trigger" style="margin-left: 5px;" type="success">上传样本报告</el-button>
            <div slot="tip" class="el-upload__tip"></div>
          </el-upload>
        </div>
      </div>
    </el-dialog>

    <el-dialog width="500px" :visible.sync="checkSampleDataVisible" title="样本数据校验" :close-on-click-modal="false">
      <p v-if="diffDataList.length != 0" style="color: red; text-align: center;">数据校验完成，共存在 {{ diffDataList.length }}
	        项KEY缺失，请检查服务器样本文件是否正确！</p>
      <p v-if="diffDataList.length == 0" style="color: green; text-align: center;">数据校验完成，不存在KEY缺失情况</p>
      <el-button type="success" style="margin-top: 10px; margin-bottom: 10px;" @click="genePdfReport">继续生成报告</el-button>
      <el-switch style="margin-left: 10px;" v-model="geneCoverContent" active-text="封面加姓名" inactive-text="封面"></el-switch>
      <el-table v-loading="loading" :data="diffDataList" highlight-current-row border height="500px">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" width="55" type="index" />
        <el-table-column label="KEY" prop="key" />
        <el-table-column label="#"><span style="color: red;">缺失</span></el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog width="800px" :visible.sync="showGenePdfUrlVisible" title="预览样本报告" :close-on-click-modal="false">
      <iframe id="iframeDiv" width="100%" height="620px" frameborder="no" allowtransparency="true"
        :src="htmlPdUrl"></iframe>
      <el-button type="primary" style="margin-top: 5px; margin-bottom: 5px; float: right;"
        @click="geneReportEnd">完成</el-button>
    </el-dialog>

    <el-dialog width="600px" :visible.sync="editInputParamDialogVisiable" title="编辑样本流程参数" :close-on-click-modal="false">
      <el-radio v-model="sysGene" label="true">使用系统参数</el-radio>
      <el-radio v-model="sysGene" label="false">使用自定义参数</el-radio>
      <codemirror style="margin-top: 10px;" v-if="sysGene == 'false'" class="runArgsContent" ref="codemirrorRetEdit"
        v-model="processInputParamJson" :options="cmOptions" />
      <el-button style="margin-top: 5px; margin-bottom: 5px; float: right; margin-left: 12px;"
        @click="closeEditInputParam">取消</el-button>
      <el-button type="primary" style="margin-top: 5px; margin-bottom: 5px; float: right; margin-left: 10px;"
        @click="updateProcessInput">保 存</el-button>
    </el-dialog>

    <el-dialog width="600px" :visible.sync="surveyDialogVisiable" title="样本问卷信息" :close-on-click-modal="false">
      <el-descriptions title="问卷回答信息" :column="1">
        <el-descriptions-item :key="item.key" v-for="item in answerJsonList" :label="item.key">{{ item.val
        }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <viewDetails-page :viewDetailsDataPro="viewDetailsDataPro" v-if="viewDetailsData"
      @close="closeDetail"></viewDetails-page>

    <seqSampleReport :checkedSeqSample="checkedSample" v-if="viewReportData"
      @close="closeSampleReport"></seqSampleReport>

  </div>
</template>

<script>
import viewDetailsPage from "../reportSample/detalis/index"
import seqSampleReport from "../reportSample/report/index"
import reportTemplateApi from '@/api/report/template'
import dfApplicationApi from '@/api/analysis/application';
import { Session } from '@/utils/storage';
import { formatDate } from '@/utils/formatTime';
import reportSampleApi from '@/api/report/reportSample';
import reportIndexApi from '@/api/report';
import seqSampleApi from '@/api/sequence/seqSample';

import seqSampleReportApi from '@/api/sequence/seqSampleReport';

import { codemirror } from 'vue-codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/mode/javascript/javascript.js';
import "codemirror/mode/markdown/markdown.js";
import 'codemirror/mode/css/css.js';
import 'codemirror/mode/vue/vue.js';
import './setting.js';
export default {
  name: '',
  components: {
    viewDetailsPage,
    seqSampleReport
  },
  data() {
    return {
      geneCoverContent: true,
      queryParams: {
        number: '',
        userName: '',
        status: '',
        // pageNum: 0,
        // pageSize: 10,
        // statuses: ['REPORT_AUDIT', 'COMPLETED'],
        // status: '',
      },

      viewDetailsData: false,
      viewReportData: false,
      viewDetailsDataPro: {},
      loading: false,
      dataList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,

      rules: {},

      cmOptions: {
        tabSize: 2, // tab
        styleActiveLine: true,
        lineNumbers: true, // 换行操作
        lineWrapping: true, // 换行操作
        styleSelectedText: true,
        line: true,
        foldGutter: true,
        gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
        highlightSelectionMatches: { showToken: /\w/, annotateScrollbar: true },
        mode: 'application/json',
        hintOptions: {
          completeSingle: false,
        },
        keyMap: 'sublime',
        matchBrackets: true,
        showCursorWhenSelecting: true,
        theme: 'monokai',
        // theme: 'solarized',
        extraKeys: {},
      },
      processInputParamJson: '',
      sysGene: 'true',

      viewFileVisible: false,
      inputFileData: [],
      outputFileData: [],
      viewFileSampleId: '',
      input_uploadAction: '',
      out_uploadAction: '',
      headers: {},

      statusMap: {
        CREATE: '已创建',
        TO_BE_SENT_OUT: '待寄出',
        SENT_OUT: '已寄出',
        SAMPLE_RECEIVE: '样本已收到',
        REPORT_SEQ_END: '实验室测序完成',
        DATA_ANALYSIS: '数据分析中',
        REPORT_AUDIT: '样本审核中',
        COMPLETED: '完成',
      },

      pdfUrl: '',
      previewDialog: {},
      applicationList: [],

      editDialog: false,
      formData: {},

      uploadFastqDialog: {},
      checkedSample: {},
      uploadFastqFormData: {},

      uploadReportPdfVisible: false,
      uploadReportPdfAction: '',
      uploadReport: 'true',

      checkSampleDataVisible: false,
      diffDataList: [],
      htmlPdUrl: '',
      showGenePdfUrlVisible: false,
      appTemplateList: [],

      editInputParamDialogVisiable: false,

      surveyDialogVisiable: false,
      answerJsonList: [],

      activeName: 'first',
      activeSampleType: 'REPORT',

      downloadSampleReportId: '',

      sendKafkaDialog: {},
      sxProcessList: [],
    };
  },
  mounted() {
    this.headers = {
      Authorization: 'Bearer ' + localStorage.getItem('token'),
    };
  },
  created() {
    this.getReportSampleData('REPORT');
  },
  methods: {

    closeSendKafkaDialog () {
      this.$set(this.sendKafkaDialog, 'visible', false);
    },
    submitSendKafka () {
      reportSampleApi.sendKafka(this.checkedSample.id).then((res) => {
	        this.$message({ message: '报告样本已发送至Kafka！', type: 'success' });
        this.getReportSampleData(this.activeSampleType);
      });
    },

    sampleReportPage (row) {
      this.checkedSample = row;
      this.viewReportData = true;
    },
    tabsChangeClick (tab) {
      this.activeName = tab.name;
      this.viewDetailsData = false;
      this.viewReportData = false;
      switch (this.activeName) {
        case 'first':
          this.activeSampleType = 'REPORT';
          this.getReportSampleData('REPORT');
          break;
        case 'second':
          this.activeSampleType = 'FMT';
          this.getReportSampleData('FMT');
          break;
        case 'third':
          this.activeSampleType = 'CHECK_UP';
          this.getReportSampleData('CHECK_UP');
          break;
        case 'patient':
          this.activeSampleType = 'PATIENT';
          this.getReportSampleData('PATIENT');
          break;
      }
    },
    sampleTemplateFilePath (id) {
      seqSampleApi.getSampleTemplateFilePath(id).then(res => {
        if (res.data == '') {
          this.$message.error('复制失败，当前样本没有上传输出文件！');
          return;
        }
        this.$copyText(res.data);
        this.$message({ message: '已复制到剪切板！', type: 'success' });
      })
    },
    delSampleTemplateFile (row) {
      this.$confirm('此操作将删除本地模板文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        seqSampleApi.delSampleTemplateFile(row.id).then(res => {
          this.$message({ message: '样本模板文件删除成功！', type: 'success' });
          this.getReportSampleData(this.activeSampleType);
        })
      }).catch(() => {});
    },
    copyApplicationTemplate (row) {
      this.$confirm('此操作将基于当前应用模板生成样本模板文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        seqSampleApi.copyApplicationTemplate(row.id).then(res => {
          this.$message({ message: '样本模板文件生成成功！', type: 'success' });
          this.getReportSampleData(this.activeSampleType);
        })
      }).catch(() => {});
    },
    // 查看
    viewDetails(row) {
      row.activeSampleType = this.activeSampleType;
      this.viewDetailsDataPro = row;
      this.viewDetailsData = true;
    },
    closeDetail() {
      this.viewDetailsData = false;
    },
    closeSampleReport () {
      this.viewReportData = false;
    },
    openSurveyDialog(row) {
      this.surveyDialogVisiable = true;
      this.checkedSample = row;
      let answerJson = row.answerJson;
      if (answerJson) {
        answerJson = JSON.parse(answerJson)
        let answerJsonList = [];
        for (let k in answerJson) {
          answerJsonList.push({
            key: k,
            val: answerJson[k]
          })
        }
        this.answerJsonList = answerJsonList;
      }
    },
    markSampleDataFile(row) {
      const loading = this.$loading({
        lock: true,
        text: '数据标记中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      this.$confirm('标记状态为【数据分析中】，确认服务器已经上传Rgenerate文件?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        reportSampleApi.markDataAnalysis(row.id).then(res => {
          loading.close();
          this.$message({ message: '报告样本标记成功！', type: 'success' });
          this.getReportSampleData(this.activeSampleType);
        })
      }).catch(() => { });
    },
    openSampleFileDatatDialog(row) {
      this.checkedSample = row;
      reportSampleApi.existSampleData(row.id).then(res => {
        let data = res.data;
        if (data) {
          this.$confirm('检测到此样本中已上传数据文件，是否重新上传?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.input_uploadAction = process.env.VUE_APP_FILE_API_PREV + '/service-platform/sample-file/upload/' + row.id + '?type=INPUT'; //输入文件
            this.out_uploadAction = process.env.VUE_APP_FILE_API_PREV + '/service-platform/sample-file/upload/' + row.id + '?type=OUTPUT'; // 输出文件
            this.checkedSample = row;
            this.viewFileSampleId = row.id;
            this.viewFileVisible = true;
            this.getFile();
          }).catch(() => { });
        } else {
          this.input_uploadAction = process.env.VUE_APP_FILE_API_PREV + '/service-platform/sample-file/upload/' + row.id + '?type=INPUT'; //输入文件
          this.out_uploadAction = process.env.VUE_APP_FILE_API_PREV + '/service-platform/sample-file/upload/' + row.id + '?type=OUTPUT'; // 输出文件
          this.checkedSample = row;
          this.viewFileSampleId = row.id;
          this.viewFileVisible = true;
          this.getFile();
        }
      })
    },
    updateProcessInput() {
      reportSampleApi.updateInputParam({
        id: this.checkedSample.id,
        processInputParamJson: this.processInputParamJson,
        sysGene: this.sysGene
      }).then(res => {
        this.$message({ message: '编辑参数成功！', type: 'success' });
        this.closeEditInputParam();
        this.getReportSampleData(this.activeSampleType);
      })
    },
    openEditInputParam(row) {
      this.checkedSample = row;
      this.editInputParamDialogVisiable = true;
      seqSampleApi.get(row.id).then(res => {
        this.processInputParamJson = res.data.processInputParamJson ? res.data.processInputParamJson : '';
      })
    },
    closeEditInputParam() {
      this.editInputParamDialogVisiable = false;
    },
    copyFileUrl(id) {
      seqSampleApi.getSampleFileUrl(id).then(res => {
        if (res.data == '') {
          this.$message.error('复制失败，当前样本没有上传输出文件！');
          return;
        }
        this.$copyText(res.data);
        this.$message({ message: '已复制到剪切板！', type: 'success' });
      })
    },
    changeApplication(val) {
      this.appTemplateList = [];
      this.formData = {
        dfApplicationId: this.formData.dfApplicationId
      }
      reportTemplateApi.listByApplication(val).then(r => {
        this.appTemplateList = r.data;
        this.formData = row;
      })
    },
    geneReportEnd() {
      this.showGenePdfUrlVisible = false;
      this.getReportSampleData(this.activeSampleType);
    },
    genePdfReport() {
      const loading = this.$loading({
        lock: true,
        text: 'PDF 解析中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      reportSampleApi.parseReport(this.checkedSample.id).then(res1 => {
        if (res1.error) {
          this.$message({
            showClose: true,
            message: res1.data,
            type: 'error',
            duration: 0,
            customClass: 'messageErrorClass'
          });
          loading.close();
          return;
        }
        reportIndexApi.genePdf(this.checkedSample.reportTemplateId, true, this.checkedSample.id, this.geneCoverContent).then((res) => {
          loading.close();
          let result = res;
          var binaryData = [];
          binaryData.push(result);
          let Blobs = new Blob(binaryData, { type: 'application/pdf' });
          this.htmlPdUrl = URL.createObjectURL(Blobs);
          this.checkSampleDataVisible = false;
          this.viewFileVisible = false;
          this.showGenePdfUrlVisible = true;
        });
      })
    },
    submitReportInfo() {
      reportSampleApi.uploadSampleReportNonFile(this.checkedSample.id).then(res => {
        this.$message({ message: '样本报告已提交！', type: 'success' });
        this.closeUploadFastqDialog();
        this.getReportSampleData(this.activeSampleType);
      })
    },
    openUploadReportDialog(row) {
      this.checkedSample = row;
      this.uploadReportPdfVisible = true;
      this.uploadReportPdfAction = process.env.VUE_APP_FILE_API_PREV + '/service-platform/seq-report-sample/upload-report/' + row.id;
    },
    uploadReportFileSuccess() {
      this.uploadReportPdfVisible = false;
      this.$message({ message: '文件上传成功！', type: 'success' });
      this.getReportSampleData(this.activeSampleType);

    },
    submitUploadReport() {
      this.$refs.uploadReport.submit();
    },
    uploadFastq() {
      let uploadFastqFormData = this.uploadFastqFormData;
      uploadFastqFormData.id = this.checkedSample.id;
      reportSampleApi.uploadFastqFile(uploadFastqFormData).then(res => {
        this.$message({ message: 'FastQ 文件上传成功！', type: 'success' });
        this.$set(this.uploadFastqDialog, 'visible', false);
        this.getReportSampleData(this.activeSampleType);
      })
    },
    closeUploadFastqDialog() {
      this.$set(this.uploadFastqDialog, 'visible', false);
    },
    openUploadFastqDialog(row) {
      this.$set(this.uploadFastqDialog, 'visible', true);
      this.$set(this.uploadFastqDialog, 'title', '上传fastq文件');
      this.checkedSample = row;
    },
    saveApplication() {
      reportSampleApi.setDfApplication(this.checkedSample.id, this.formData.dfApplicationId, this.formData.reportTemplateId).then(res => {
        this.editDialog = false;
        this.$message({ message: '样本所属应用设置成功！', type: 'success' });
        this.getReportSampleData(this.activeSampleType);
      })
    },
    openEditApplication(row) {
      this.checkedSample = row;
      dfApplicationApi.list().then(res => {
        this.applicationList = res.data;
        this.editDialog = true;
        if (this.applicationList.length != 0) {
          reportTemplateApi.listByApplication(this.applicationList[0].id).then(r => {
            this.appTemplateList = r.data;
            this.formData = row;
          })
        } else {
          this.formData = row;
        }
      })
    },
    closeEditDialog() {
      this.editDialog = false;
    },
    sendKafka(row) {
      this.checkedSample = row;
      this.$set(this.sendKafkaDialog, 'visible', true);
    },
    closePreviewDialog() {
      this.$set(this.previewDialog, 'visible', false);
    },
    downlaodPdf () {
      if (this.downloadSampleReportId) {
        seqSampleReportApi.downloadReport(this.downloadSampleReportId).then((res) => {
          const blob = new Blob([res], {
            type: 'application/pdf'
          })
          let link = document.createElement('a')
          let body = document.querySelector('body')
          link.href = window.URL.createObjectURL(blob)
          link.style.display = 'none'
          link.download = this.checkedSample.number + '.pdf'
          body.appendChild(link)
          link.click()
          body.removeChild(link)
          window.URL.revokeObjectURL(link.href)
        });
      } else {
        this.$message({ message: '无可下载报告！', type: 'error' });
      }
      
    },
    samplePdf(row) {
      this.checkedSample = row;
      seqSampleReportApi.newestReport(row.id).then(res => {
        let data = res.data;
        if (data.id) {
          this.$set(this.previewDialog, 'title', '预览样本报告');
          this.$set(this.previewDialog, 'visible', true);
          // reportSampleApi.downloadReport(data.id).then((res) => {
          //   const binaryData = [];
          //   binaryData.push(res);
          //   this.pdfUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }));
          // });
          this.downloadSampleReportId = data.id;
          seqSampleReportApi.downloadReport(data.id).then((res) => {
            const binaryData = [];
            binaryData.push(res);
            let blob = new Blob(binaryData, { type: 'application/pdf' });
            this.pdfUrl = window.URL.createObjectURL(blob) + '#toolbar=0&navpanes=0&scrollbar=0';
          });
        } else {
          this.$message({ message: '当前样本未生成报告，请生成报告之后再查看！', type: 'error' });
        }
      })
    },
    syncSample() {
      reportSampleApi.syncSampleSystem().then((res) => {
        this.$message({ message: '样本数据同步成功！', type: 'success' });
        this.getReportSampleData('REPORT');
      });
    },
    // 样本报告数据
    getReportSampleData(type) {
      if (!type) {
        type = 'REPORT'
      }
      let criteriaVos = [{
        name: 'sampleType',
        searchType: 'EQUAL',
        searchVal: type
      }];
      if (this.queryParams.number) {
        criteriaVos.push({
          name: 'number',
          searchType: 'LIKE',
          searchVal: this.queryParams.number
        })
      }
      if (this.queryParams.userName) {
        criteriaVos.push({
          name: 'userName',
          searchType: 'LIKE',
          searchVal: this.queryParams.userName
        })
      }
      if (this.queryParams.status) {
        criteriaVos.push({
          name: 'sampleStatus',
          searchType: 'EQUAL',
          searchVal: this.queryParams.status
        })
      }
      let sortField = 'createTime';
      if (type == 'REPORT') {
        sortField = 'signDate';
      }
      let param = {
        number: this.currentPage,
        size: this.pageSize,
        sortField: sortField,
        criteriaVos: criteriaVos
      };
      reportSampleApi.reportSampleData(param).then((res) => {
        let data = res.data;
        data.content.forEach((v) => {
          v.createTimeText = formatDate(new Date(v.syncTime), 'YYYY-mm-dd HH:MM:SS');
          v.statusText = this.statusMap[v.sampleStatus];
        });
        this.dataList = data.content;
        this.total = data.count;
      });
    },
    // 重置
    resetQuery() {
      this.queryParams = {
        keywords: '',
        pageNum: 0,
        pageSize: 10,
        statuses: ['REPORT_AUDIT', 'COMPLETED'],
        status: '',
      };
      this.getReportSampleData(this.activeSampleType);
    },
    // 查看文件
    viewFile(row) {
      this.checkedSample = row;
      this.geneCoverContent = true;
      reportSampleApi.diff(this.checkedSample.id).then(res => {
        let data = res.data;
        this.checkSampleDataVisible = true;
        this.diffDataList = data;
      })
    },
    getFile() {
      reportSampleApi.getFileList(this.viewFileSampleId).then((res) => {
        let fileData = res.data;
        let outOutData = [];
        let inputData = [];
        fileData.forEach((i) => {
          if (i.fileType == 'OUTPUT') {
            outOutData.push(i);
          }
          if (i.fileType == 'INPUT') {
            inputData.push(i);
          }
        });
        this.outputFileData = outOutData;
        this.inputFileData = inputData;
      });
    },
    submitUpload() {
      this.$refs.uploadinput.submit();
    },
    submitUpload_out() {
      this.$refs.upload.submit();
    },
    uploadFileSuccess() {
      this.$message({ message: '文件上传成功！', type: 'success' });
      this.getFile();
    },
    uploadFileSuccess_out() {
      this.$message({ message: '文件上传成功！', type: 'success' });
      this.viewFileVisible = false;
      // reportSampleApi.diff(this.checkedSample.id).then(res => {
      //   let data = res.data;
      //   this.checkSampleDataVisible = true;
      //   this.diffDataList = data;
      // })
    },

    handleSizeChange(val) {
      this.pageSize = val * 1;
      this.getReportSampleData(this.activeSampleType);
    },
    handleCurrentChange(val) {
      this.currentPage = val * 1;
      this.getReportSampleData(this.activeSampleType);
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (column.property == 'number') {
        return {
          cursor: 'pointer',
        };
      }
    },
  },
};
</script>

<style>
.messageErrorClass .el-message__content {
  max-height: 300px;
  overflow: auto;
}
</style>
<style scoped>
.block {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}

.viewFileVisible_box {
  display: flex;
}

.input_file {
  width: 50%;
  border: 1px solid #dcdfe6;
  padding: 2% 1%;
  margin-right: 2%;
}

.output_file {
  width: 100%;
  border: 1px solid #dcdfe6;
  padding: 2%;
}

.input_file_top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 2%;
}
</style>